package online.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @Auther: 狼芒
 * @Date: 2021/11/11 22:13
 * @Descrintion: 延迟队列配置类
 * @version: 1.0
 */
@Configuration
public class DelayedQueueConfig {

    //交换机
    public static final String DELAYED_QUEUE = "delayed_queue";
    //队列
    public static final String DELAYED_EXCHANGE = "delayed_exchange";
    //路由Key
    public static final String DELAYED_ROUTING_KEY = "delayed_routing_key";
    //交换机类型
    public static final String EXCHANGE_TYPE = "x-delayed-message";

    /**
     * 声明一个队列
     * @return
     */
    @Bean
    public Queue delayedQueue() {
        return new Queue(DELAYED_QUEUE);
    }

    /**
     * 声明基于插件的交换机
     */
    @Bean
    public CustomExchange dalayExchange() {
        HashMap<String, Object> arguments = new HashMap<>(2);
        //设置延迟类型，直接类型
        arguments.put("x-delayed-type", "direct");
        /**
         * 1、交换机名称
         * 2、交换机类型
         * 3、是否需要持久化
         * 4、是否需要自动删除
         * 5、其他的参数
         */
        return new CustomExchange(DELAYED_EXCHANGE, EXCHANGE_TYPE, true, false, arguments);
    }

    /**
     * 绑定交换机与队列
     */
    @Bean
    public Binding delayedQueueBindingDalayExchange(@Qualifier("delayedQueue") Queue delayedQueue,  @Qualifier("dalayExchange") CustomExchange dalayExchange) {
        return BindingBuilder.bind(delayedQueue).to(dalayExchange).with(DELAYED_ROUTING_KEY).noargs();
    }
}
